package com.smzd.ccms.complets;

import java.net.URLDecoder;
import java.util.List;

import com.smzd.ccms.business.CommentService;
import com.smzd.ccms.core.AbstractCompletPlugin;
import com.smzd.ccms.core.ParamsWrapper;
import com.smzd.ccms.domain.Channel;
import com.smzd.ccms.domain.Comment;
import com.smzd.framework.utils.db.RPage;

import freemarker.core.Environment.Namespace;

public class CommentListComplet extends AbstractCompletPlugin {
	CommentService service;

	public CommentListComplet(int id) {
		super(id);
		service = CommentService.getInstance();
	}

	@Override
	public String execute(ParamsWrapper params, Namespace currentNameSpace) throws Exception {
		if (service == null) {
			synchronized (this) {
				if (service == null) {
					service = CommentService.getInstance();
				}
			}
		}
		Integer id = params.getParamValue("id", 0);
		List<Comment> comments = null;
		if (id == 0 || id.intValue() <= 0) {
			Integer chId = params.getParamValue("chId", 0);
			if (chId == null || chId == 0) {
				Channel ch = params.getEntityWrapper().getChannel();
				chId = ch.getId();
			}
			comments = service.getCommentsForFirstArticle(chId);
		} else {
			RPage<Comment> page = new RPage<>();
			page.setPageSize(999);
			page.setId(id);
			service.getCommentsForArticle(page);
			comments = page.getElems();
		}
		if (comments == null) {
			return null;
		}
		for (Comment comment : comments) {
			try {
				comment.setContent(URLDecoder.decode(comment.getContent(), "utf-8"));
			} catch (Exception e) {
			}
		}
		params.put("comments", comments);
		return params.getParamValue("view", "comments.ftl");
	}

}
